package api

import (
	"bpic/assert"
	"bpic/config"
	"bpic/model"
	"gitee.com/blue0121/gblue/route"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

func Index(ctx route.Context) {
	query := getQueryPath(ctx.GetRequest())

	list, err := readDir(query)
	if err != nil {
		log.Println(config.RootPath, " not exist")
		ctx.GetResponse().WriteHeader(404)
		return
	}
	//tpl := template.Must(template.New("index").Parse(assert.IndexTpl))
	//tpl.Execute(ctx.GetResponse(), list)
	err = assert.Template.ExecuteTemplate(ctx.GetResponse(), "index.html", list)
	if err != nil {
		log.Print(err)
	}
}

func getQueryPath(r *http.Request) string {
	path := r.URL.Query().Get("path")
	if path == "" {
		path = "/"
	}
	return path
}

func readDir(query string) (*model.List, error) {
	path := model.NewPath(config.RootPath)
	path.AddPath(query)

	files, err := ioutil.ReadDir(path.ToString())
	if err != nil {
		return nil, err
	}
	list := model.NewList(path)
	for _, file := range files {
		name := file.Name()
		if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "$") {
			continue
		}
		href := model.NewPath(query)
		href.AddPath(name)
		link := "/index?path=" + href.ToString()
		if file.IsDir() {
			list.AddDirItem(&model.DirItem{name, link})
		} else if isPic(name) {
			list.AddFileItem(&model.FileItem{name, href.ToString()})
		}
	}
	return list, nil
}

func isPic(name string) bool {
	return strings.HasSuffix(name, ".jpg") ||
		strings.HasSuffix(name, ".jpeg") ||
		strings.HasSuffix(name, ".png")
}
